package com.example.springboot2022nocv.tengxunapi;

import com.alibaba.fastjson.JSONObject;
import com.example.springboot2022nocv.entity.ChinaTotal;
import com.example.springboot2022nocv.service.ChinaTotalService;
import com.example.springboot2022nocv.service.lmpl.ChinaTotalServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.logging.SimpleFormatter;

@Component
public class ChinaTotalScheduleTask {
    @Autowired
    ChinaTotalService chinaTotalService;

    //@Scheduled(fixedDelay = 10000)//10s一次更新
    public void updateChinaTotalToDB() throws Exception{
        HttpUtils httputils = new HttpUtils();
        String string = httputils.getData();
        System.out.println("数据:"+string);
        // 1.所有数据的alibaba格式
        JSONObject jsonObject = JSONObject.parseObject(string);
        Object data = jsonObject.get("data");
        System.out.println("data: "+data);
        // 2.data
        JSONObject jsonobjectData = JSONObject.parseObject(data.toString());
        Object chinaTotal = jsonobjectData.get("chinaTotal");
        Object lastUpdateTime = jsonobjectData.get("overseaLastUpdateTime");
        System.out.println("chinaTotal : "+chinaTotal);
        //3.total全中国整体疫情数据
        JSONObject jsonobjectTotal = JSONObject.parseObject(chinaTotal.toString());
        Object total = jsonobjectTotal.get("total");
        System.out.println("total : "+total);
        //4.全国数据total
        JSONObject totalData = JSONObject.parseObject(total.toString());
        Object confirm = totalData.get( "confirm");
        Object input = totalData.get( "input");
        Object severe = totalData.get( "severe");
        Object heal = totalData.get( "heal");
        Object dead = totalData.get( "dead");
        Object suspect = totalData.get( "suspect");

        ChinaTotal dataEntity = new ChinaTotal();
        dataEntity.setConfirm((Integer) confirm);
        dataEntity.setInput((Integer) input);
        dataEntity. setSevere( (Integer) severe);
        dataEntity.setHeal((Integer)heal);
        dataEntity.setDead((Integer)dead);
        dataEntity.setSuspect((Integer) suspect);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dataEntity.setUpdateTime(format.parse(String.valueOf(lastUpdateTime)));

        //6.插入数据库
        chinaTotalService.save(dataEntity);
    }
}
